package com.gdust.hzx.manager.service.impl;

import com.gdust.hzx.manager.service.FileUploadService;
import com.gdust.hzx.manager.properties.TencentCloudProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * ClassName: FileUploadServiceImpl
 * Package: com.gdust.spzx.manager.service.impl
 * Description:
 *
 * @Author syun
 * @Create 2024/11/23 17:20
 * @Version 1.0
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;


    /**
     * 用户头像上传接口
     * @param file 上传文件
     * @return 文件名
     */
    @Override
    public String upload(MultipartFile file) {

        // 1. 初始化用户身份信息（secretId, secretKey）
        String secretId = tencentCloudProperties.getSecretId();
        String secretKey = tencentCloudProperties.getSecretKey();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        // 2. 设置 bucket 的地域, COS 地域
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https); // 使用 https 协议

        // 3. 生成 COS 客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 4. 设置文件元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());

        // 5. 构造文件路径和文件名 (使用日期 + UUID + 原始文件名)
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                "/" + UUID.randomUUID().toString().replaceAll("-", "") + "-" + file.getOriginalFilename();

        // 6. 构建 PutObjectRequest 请求
        PutObjectRequest putObjectRequest;
        try {
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),
                    filename,
                    file.getInputStream(),
                    meta);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }

        // 7. 设置存储类型并上传文件
        putObjectRequest.setStorageClass(StorageClass.Standard);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown(); // 关闭客户端

        // 8. 构造并返回完整的文件访问 URL
        String fileUrl = String.format("https://%s.cos.%s.myqcloud.com/%s",
                tencentCloudProperties.getBucketPrivate(), // 存储桶名称
                tencentCloudProperties.getRegion(),        // 区域
                filename);                                  // 文件路径
        return fileUrl;
    }

}
